package com.lightsh.coverflow;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

/**
 * coverflow用到的adapter类
 */
public class CoverFlowAdapter extends BaseAdapter{
	
	// 图片的x轴放大比例
	public static final float IMAGE_X_SCALL_RANGE = 0.5f;
	private List<Bitmap> mBitmaps;
	private Context mContext;
	public CoverFlowAdapter(List<Bitmap> bitmaps, Context context){
		mBitmaps = bitmaps;
		mContext = context;
	}

	public int getCount() {
		return mBitmaps.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}
	
	private int mViewHeight = -1;
	private int mViewWidth = -1;
	
	public void setViewSize(int width, int height){
		mViewHeight = height;
		mViewWidth = width;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// 这里可以返回任何view
		// 为了能够使用固定大小的view，并且中间的图片使用适配图片大小的拉伸比例(类似ScaleType.CENTER_INSIDE)绘制类型，
		// 我们需要将ImageView放入layout中
		LinearLayout layout = new LinearLayout(mContext);
		layout.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		
		ImageView imageView = new ImageView(mContext);
		imageView.setScaleType(ScaleType.FIT_XY);
		
		// FIXME 不要每次都做转换，消耗时间
		Bitmap bm = ImageUtility.createReflectedImage(mBitmaps.get(position));
		imageView.setImageBitmap(bm);
		
		LinearLayout.LayoutParams linearParams;
		if(mViewHeight > 0 && mViewWidth > 0){
			// 需要计算图片的比例高度(或者宽度),根据比例判断哪个需要使用fillparent
			
			int height = LinearLayout.LayoutParams.FILL_PARENT;
			int width = LinearLayout.LayoutParams.FILL_PARENT;
			
			float scaleBitmap = ((float)bm.getHeight()) / bm.getWidth();
			float scaleView = ((float)mViewHeight) / mViewWidth;
			if(scaleBitmap > scaleView){
				// 图片高度比例大，即高度fillparent，宽度需要计算
				width = (int)(mViewHeight / scaleBitmap * IMAGE_X_SCALL_RANGE);
			}else{
				height = (int)(scaleBitmap * mViewWidth);
			}
			
			linearParams = new LinearLayout.LayoutParams(width, height);
			layout.setLayoutParams(new Gallery.LayoutParams((int)(mViewWidth*IMAGE_X_SCALL_RANGE), mViewHeight));
		}else{
			// 这里使用fillparent就可以了
			linearParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);			
			layout.setLayoutParams(new Gallery.LayoutParams((int)(bm.getWidth()*IMAGE_X_SCALL_RANGE), bm.getHeight()));
		}
		imageView.setLayoutParams(linearParams);
		layout.addView(imageView);
		
		return layout;
	}
}